# -*- coding:utf-8 -*-

__author__='zhaoxp'

from collections import defaultdict

'''
简单的接口应该接受函数，而不是类的实例

这里注意nonlocal这个关键字是python3中的特性，2中么有该功能
'''

def log_missing():
    print('key added')
    return 0
current = {'green':12,'blue':3}
increments=[('red',5),('blue',17),('orange',9)]

added_count=0

def increment_with_report(current,increments):
    global added_count
    
    def missing():
        #nonlocal added_count # for python 3.*
        global added_count
        added_count+=1
        return 0
    
    result=defaultdict(missing,current)
    for key,amount in increments:
        result[key]+=amount
    
    return result,added_count


class CountMissing(object):
    def __init__(self):
        self.count=0
    def missing(self):
        self.count+=1
        return 0


class BetterCountMissing(object):
    def __init__(self):
        self.count=0
        
    def __call__(self):
        self.count += 1
        return 0

def test1():
    result=defaultdict(log_missing,current)
    print('result = %s'%result)
    print('before:',dict(result))
    for key,amount in increments:
        result[key]+=amount
    print('after',dict(result))


def test2():
    result,count=increment_with_report(current,increments)
    print('result = %s'%result)
    print('count = %s'%count)


def test3():
    counter = CountMissing()
    result = defaultdict(counter.missing,current)
    for key,amount in increments:
        result[key] += amount
    print('counter.count = %s'%counter.count)


def test4():
    counter = BetterCountMissing()
    result = defaultdict(counter,current)
    for key,amount in increments:
        result[key] += amount
    print('counter.count = %s'%counter.count)


if __name__=='__main__':
    print('')
    test1()
    print('-'*30)
    test2()
    print('-'*30)
    test3()
    print('-'*30)
    test4()
